package com.yuejie.musicai.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yuejie.musicai.beans.Info;
import com.yuejie.musicai.services.impl.AccountServiceImpl;

/**
 * @author leilz
 * @date 2012-7-19
 * TODO 用户权限验证
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
        
		HttpSession session = request.getSession(true);
		if(request.getServletPath().equals("/account/logout")){
			session.removeAttribute("user");
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HttpSession session = request.getSession(false);
		String path = request.getServletPath();
		
		if(path.equals("/account/dologin")){
			String user = request.getParameter("user");
			String password = request.getParameter("password");
			Info info = new AccountServiceImpl().login(user, password);
			
			if(info.getMessage().equals("success")){
				session.setAttribute("user",user);
				session.setMaxInactiveInterval(1800);
			}
		}else{
//			String user = (String) session.getAttribute("user");
//			if(user == null && !path.equals("/account/login") && !path.equals("/account/apply")){
//			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
	}
}
